/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  MainZhiShiActivity.java   
 * @Package com.jiyi.activity.main   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-6-23 上午10:02:35   
 * @version V1.0     
 */
package com.jiyi.activity.new_maintenance;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiyi.adapter.DividerItemDecoration;
import com.jiyi.adapter.recyclerview.CommonAdapter;
import com.jiyi.adapter.recyclerview.base.ViewHolder;
import com.jiyi.adapter.recyclerview.wrapper.EmptyWrapper;
import com.jiyi.bean.main.NewsListJson.NewsBean;
import com.jiyi.bean.maintenance.HireUnitBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.event.HireListEvent;
import com.jiyi.inteface.WebApi;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.DialogTool;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @ClassName: MainZhiShiActivity
 * @Description:TODO(这里用一句话描述这个类的作用)
 * @author: HYM
 * @date: 2017-6-23 上午10:02:35
 * 
 */
public class AllHireRelativeFragment extends Fragment implements
		OnRefreshListener {

	List<NewsBean> newsList = new ArrayList<NewsBean>();
	LayoutInflater inflater;
	@BindView(R.id.mainList)
	RecyclerView mListView;
	@BindView(R.id.refreshLayout)
	SwipeRefreshLayout refreshLayout;
	private List<HireUnitBean> companyBeans = new ArrayList<HireUnitBean>();
	EmptyWrapper adapter;
	ViewGroup container;
	//0 已申请 1 已绑定 2 申请解除中 3 已解除
	int type;

	Dialog dialog;

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_all_wx_task, null, false);
		ButterKnife.bind(this, view);
		this.inflater = inflater;
		this.container = container;
		init();
		return view;
	}
	
	@Subscribe
	public void onRefresh(HireListEvent hireListEvent)
	{
		if (type == hireListEvent.type) {
			companyBeans.remove(hireListEvent.position);
			adapter.notifyDataSetChanged();
		}
	}

	@Override
	public void onDestroyView() {
		DialogTool.hideDialog(dialog);
		EventBus.getDefault().unregister(this);
		super.onDestroyView();
	}

	private void init() {
		getIntentData();
		getData();
		setAdapter();
		EventBus.getDefault().register(this);
	}

	/**
	 * @author: HYM
	 * @Title: getIntentData
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-8-30
	 */
	private void getIntentData() {
		type = getArguments().getInt("type", 0);
	}


	@Override
	public void onDestroy() {
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	private void getData() {

		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("type", (type + 1) + "");
		VolleyRequest.StringRequestPost(getContext(),
				WebApi.MAINTENANCE_APPLYED_HIRE, "", params, new StringInterface(
						getContext()) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								List<HireUnitBean> tasks = new Gson().fromJson(data,
										new TypeToken<List<HireUnitBean>>() {
										}.getType());
								companyBeans.clear();
								companyBeans.addAll(tasks);
								adapter.notifyDataSetChanged();
							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							refreshLayout.setRefreshing(false);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						refreshLayout.setRefreshing(false);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

	private void setAdapter() {
		// 设置refreshLayout的监听
		refreshLayout.setColorSchemeColors(Color.RED, Color.YELLOW, Color.BLUE,
				Color.GREEN);
		refreshLayout.setOnRefreshListener(this);

		mListView.setLayoutManager(new LinearLayoutManager(getContext()));
		mListView.addItemDecoration(new DividerItemDecoration(getContext(),
				DividerItemDecoration.VERTICAL_LIST, getResources()
						.getDrawable(R.drawable.drvice_10)));

		CommonAdapter mCommonAdapter = new CommonAdapter<HireUnitBean>(getActivity(),
				R.layout.item_hire_relative, companyBeans) {
			@Override
			protected void convert(ViewHolder holder, final HireUnitBean t,
					final int position) {
				holder.setText(R.id.tvOwnerName, t.getYz_company_name());
				holder.setOnClickListener(R.id.rlRoot, new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(v.getContext(),HireDetailActivity.class);
						intent.putExtra("hire_unit", new Gson().toJson(t));
						intent.putExtra("type", type);
						intent.putExtra("position", position);
						v.getContext().startActivity(intent);
					}
				});
			}
		};

		adapter = new EmptyWrapper(mCommonAdapter);

		View emptyView = inflater.inflate(R.layout.empty_view_text_and_image,
				container, false);
		ImageView ivEmptyTip = (ImageView) emptyView
				.findViewById(R.id.ivEmptyTip);
		TextView tvEmptyTip = (TextView) emptyView
				.findViewById(R.id.tvEmptyTip);
		ivEmptyTip.setImageResource(R.mipmap.tip_empty_huodong);
		tvEmptyTip.setText(R.string.NO_DATA);
		adapter.setEmptyView(emptyView);

		mListView.setAdapter(adapter);
		adapter.notifyDataSetChanged();
	}

	@Override
	public void onRefresh() {
		getData();
	}
}
